package com.applancer.nativecmsflip;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.applancer.dataprovider.DataProvider;
import com.applancer.model.WeatherModel;
import com.applancer.parser.WeatherParser;
import com.applancer.provider.GPSTracker;
import com.applancer.provider.SystemBarTintManager;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class WeatherActivity extends Activity {

	protected TextView location;
	protected ImageView weatherIcon;
	protected TextView temperature;
	protected TextView humidity;
	protected TextView wind_direction;
	protected TextView wind_speed;
	protected TextView weather_summary;
	protected TextView now_time;

	protected WeatherModel weatherModel;

	protected TextView next1time;
	protected TextView next2time;
	protected TextView next3time;

	protected TextView temp1;
	protected TextView temp2;
	protected TextView temp3;

	protected ImageView weatherIcon1;
	protected ImageView weatherIcon2;
	protected ImageView weatherIcon3;

	protected GPSTracker gps;
	protected DataProvider dataprovider;

	protected SearchView searchView;

	protected ProgressBar indicator_load_weather;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_weather);

		handleIntent(getIntent());
	}

	@Override
	protected void onNewIntent(Intent intent) {

		handleIntent(intent);
	}

	private void handleIntent(Intent intent) {

		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
			retrieveWeatherByName(query);
			Log.e(this.getClass().toString(), query);
		} else {
			initial();
			execution();
		}
	}

	private void initial() {
		gps = new GPSTracker(this);
		dataprovider = new DataProvider(this);

		weatherModel = (WeatherModel) getIntent().getSerializableExtra("model");

		weather_summary = (TextView) findViewById(R.id.weather_summary);
		location = (TextView) findViewById(R.id.weather_location);
		weatherIcon = (ImageView) findViewById(R.id.weather_icon);
		temperature = (TextView) findViewById(R.id.temperature);
		humidity = (TextView) findViewById(R.id.weather_humidity);
		wind_direction = (TextView) findViewById(R.id.weather_wind_direction);
		wind_speed = (TextView) findViewById(R.id.weather_wind_speed);
		now_time = (TextView) findViewById(R.id.now_time);

		next1time = (TextView) findViewById(R.id.next_day_1_time);
		next2time = (TextView) findViewById(R.id.next_day_2_time);
		next3time = (TextView) findViewById(R.id.next_day_3_time);

		temp1 = (TextView) findViewById(R.id.next_day_1_temp);
		temp2 = (TextView) findViewById(R.id.next_day_2_temp);
		temp3 = (TextView) findViewById(R.id.next_day_3_temp);

		weatherIcon1 = (ImageView) findViewById(R.id.weathericon1);
		weatherIcon2 = (ImageView) findViewById(R.id.weathericon2);
		weatherIcon3 = (ImageView) findViewById(R.id.weathericon3);

		indicator_load_weather = (ProgressBar) findViewById(R.id.indicator_load_weather);
	}

	private void execution() {

		indicator_load_weather.setVisibility(View.GONE);
		getActionBar().setIcon(R.drawable.ic_detail_feed_back);
		getActionBar().setHomeButtonEnabled(true);

		location.setText(weatherModel.getLocation_name() + " , "
				+ weatherModel.getLocation_country());
		temperature.setText(weatherModel.getTemperature_top());
		humidity.setText(getString(R.string.humidity) + " "
				+ weatherModel.getHumidity());
		wind_direction.setText(getString(R.string.wind_direction) + " "
				+ weatherModel.getWind_direction());
		wind_speed.setText(getString(R.string.wind_speed) + " "
				+ weatherModel.getWind_speed());
		weather_summary.setText(weatherModel.getWeather_sumary());

		Calendar calendar = Calendar.getInstance();
		String showTime = getShowTime(calendar, ", ");
		now_time.setText(showTime);

		try {
			InputStream ims = getAssets().open(
					"weather_icon/weather_" + weatherModel.getCode() + ".png");
			Drawable d = Drawable.createFromStream(ims, null);
			weatherIcon.setImageDrawable(d);
		} catch (Exception e) {

		}

		// weatherIcon.setImageResource(R.drawable.weather_1);
		// Picasso.with(WeatherActivity.this)
		// .load(weatherModel.getIconURL())
		// .placeholder(R.drawable.ic_launcher)
		// .error(R.drawable.ic_launcher)
		// .resizeDimen(R.dimen.weather_image_size,
		// R.dimen.weather_image_size).centerInside()
		// .into(weatherIcon);

		calendar.add(Calendar.DATE, 1);
		String showTim1 = getShowTime(calendar, "\n");
		next1time.setText(showTim1);

		calendar.add(Calendar.DATE, 1);
		String showTim2 = getShowTime(calendar, "\n");
		next2time.setText(showTim2);

		calendar.add(Calendar.DATE, 1);
		String showTim3 = getShowTime(calendar, "\n");
		next3time.setText(showTim3);

		temp1.setText(weatherModel.getTemp_bottom_future().get(0) + " - "
				+ weatherModel.getTemp_top_future().get(0));
		temp2.setText(weatherModel.getTemp_bottom_future().get(1) + " - "
				+ weatherModel.getTemp_top_future().get(1));
		temp3.setText(weatherModel.getTemp_bottom_future().get(2) + " - "
				+ weatherModel.getTemp_top_future().get(2));

		try {
			InputStream ims = getAssets().open(
					"weather_icon/weather_"
							+ weatherModel.getWeather_future_code().get(0)
							+ ".png");
			Drawable d = Drawable.createFromStream(ims, null);
			weatherIcon1.setImageDrawable(d);
		} catch (Exception e) {

		}

		try {
			InputStream ims = getAssets().open(
					"weather_icon/weather_"
							+ weatherModel.getWeather_future_code().get(1)
							+ ".png");
			Drawable d = Drawable.createFromStream(ims, null);
			weatherIcon2.setImageDrawable(d);
		} catch (Exception e) {

		}

		try {
			InputStream ims = getAssets().open(
					"weather_icon/weather_"
							+ weatherModel.getWeather_future_code().get(2)
							+ ".png");
			Drawable d = Drawable.createFromStream(ims, null);
			weatherIcon3.setImageDrawable(d);
		} catch (Exception e) {

		}

		SystemBarTintManager tintManager = new SystemBarTintManager(this);
		tintManager.setStatusBarTintEnabled(true);
		tintManager.setNavigationBarTintEnabled(true);

		tintManager.setStatusBarTintResource(R.color.statusbar_bg);
		tintManager.setNavigationBarTintResource(R.color.actionbar_bg);

	}

	private String getShowTime(Calendar calendar, String regex) {
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy",
				Locale.getDefault());
		String currentDate = sdf.format(calendar.getTime());

		SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE",
				Locale.getDefault());

		Date date = calendar.getTime();
		String dayName = sdf_.format(date);
		String showTime = dayName + regex + currentDate + "";
		return showTime;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.weather, menu);

		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		searchView = (SearchView) menu.findItem(R.id.search).getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));

		return true;
	}

	@Override
	protected void onResume() {

		super.onResume();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();

		switch (id) {
		case R.id.action_settings:

			break;
		case R.id.current_location:
			Log.e(this.getClass().toString(), "current location");

			retrieveWeather();

			searchView.onActionViewCollapsed();
			searchView.setQuery("", false);
			searchView.clearFocus();
			break;
		case android.R.id.home:
			onBackPressed();
			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	private void retrieveWeather() {
		if (gps.canGetLocation()) {
			double latitude = gps.getLatitude();
			double longitude = gps.getLongitude();

			indicator_load_weather.setVisibility(View.VISIBLE);

			dataprovider.getwoeid(longitude, latitude, handlerGetWoeidWithGPS);
		} else {
			gps.showSettingsAlert();
		}
	}

	private void retrieveWeatherByName(String city) {

		indicator_load_weather.setVisibility(View.VISIBLE);
		dataprovider.getwoeidbyname(city, handlerGetWoeid);

	}

	AsyncHttpResponseHandler handlerGetWoeidWithGPS = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

			if (arg2 == null)
				return;
			String str = new String(arg2);

			try {
				JSONObject object = new JSONObject(str);
				JSONObject query = object.getJSONObject("query");
				JSONObject results = query.getJSONObject("results");

				JSONObject solze;
				try {
					JSONArray Result = results.getJSONArray("Result");
					solze = Result.getJSONObject(0);
				} catch (Exception e) {
					solze = results.getJSONObject("Result");
				}

				String woeid = solze.getString("woeid");
				Log.d(this.getClass().toString(), "success" + woeid);

				dataprovider.getWeather(woeid, handlerGetWeather);

			} catch (Exception e) {
				Toast.makeText(WeatherActivity.this, "Location not fault",
						Toast.LENGTH_SHORT).show();
				if (indicator_load_weather != null)
					indicator_load_weather.setVisibility(View.GONE);
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			Log.d(this.getClass().toString(), "fail");
			if (indicator_load_weather != null)
				indicator_load_weather.setVisibility(View.GONE);

		}
	};

	AsyncHttpResponseHandler handlerGetWoeid = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

			if (arg2 == null)
				return;
			String str = new String(arg2);

			try {
				JSONObject object = new JSONObject(str);
				JSONObject query = object.getJSONObject("query");
				JSONObject results = query.getJSONObject("results");
				JSONObject solze;
				try {
					JSONArray place = results.getJSONArray("place");
					solze = place.getJSONObject(0);
				} catch (Exception e) {
					solze = results.getJSONObject("place");
				}

				String woeid = solze.getString("woeid");
				Log.d(this.getClass().toString(), "success" + woeid);

				dataprovider.getWeather(woeid, handlerGetWeather);

			} catch (Exception e) {
				Toast.makeText(WeatherActivity.this, "Location not fault",
						Toast.LENGTH_SHORT).show();
				if (indicator_load_weather != null)
					indicator_load_weather.setVisibility(View.GONE);
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			Log.d(this.getClass().toString(), "fail");
			if (indicator_load_weather != null)
				indicator_load_weather.setVisibility(View.GONE);
		}
	};

	AsyncHttpResponseHandler handlerGetWeather = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

			if (arg2 == null)
				return;
			String str = new String(arg2);

			WeatherParser weatherparser = new WeatherParser();
			weatherModel = weatherparser.parseWeather(str);

			if (weatherModel.getCode() == null
					|| weatherModel.getCode().equals(""))
				return;
			execution();

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			Log.d(this.getClass().toString(), "fail");

		}

		public void onFinish() {
			indicator_load_weather.setVisibility(View.GONE);
		};
	};
}
